//
//  HouseLoanCalculateView.m
//  YiJuZhangShou2.0
//
//  Created by URANUS on 16/3/28.
//  Copyright © 2016年 Mr.X. All rights reserved.
//

#import "HouseLoanCalculateView.h"
#import "HouseLoanCalculateChartsView.h"
#import "Masonry.h"
#import "TextFieldUtil.h"
#import "DropdownMenuView.h"
#import "DropdownMenuViewUtil.h"
#import "LabelUtil.h"
#import "ButtonUtil.h"
#import "HouseLoanCalculateChartsModel.h"
#import "UILabel+XExtension.h"
#import "UIAlertControllerUtil.h"
@interface HouseLoanCalculateView()<UITextFieldDelegate>
@property (nonatomic, strong) HouseLoanCalculateChartsView *chartsView;
@property (nonatomic, strong) UITextField *houseTotalPriceTextField;
@property (nonatomic, strong) UITextField *priceDiscountTextField;
@property (nonatomic, strong) DropdownMenuView *downPayRateDropMenu;
@property (nonatomic, strong) DropdownMenuView *loanYearsDropMenu;
@property (nonatomic, strong) UILabel *bankRateLabel;
@property (nonatomic, strong) NSArray *loanWayTitles;
@property (nonatomic, strong) NSArray *payLoanWayTitles;
@property (nonatomic, strong) UILabel *bottomTintLabel;
@property (nonatomic, strong) UIView *keyboardMaskView;
@end

@implementation HouseLoanCalculateView
{
    CGFloat _firstPayRatio;
    NSInteger _period;
    CGFloat _ratio;
    Boolean _isCapitalCalculate;
}
#pragma mark - Initialize
- (instancetype)init
{
    self = [super init];
    if (self) {
        _isCalculate = NO;
        _loanCalculateUtil = [LoanCalculateUtil new];
        _firstPayRatio = 0.3;
        _period = 12;
        _ratio = 0.5;
        _isCapitalCalculate = YES;
        [self loadHouseLoanCalculateView];
//        self.backgroundColor = [UIColor colorWithRed:0.9294 green:0.9294 blue:0.9294 alpha:1.0];
        
    }
    return self;
}

#pragma mark - Delegate UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField endEditing:YES];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [self addSubview:self.keyboardMaskView];
    [self.keyboardMaskView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (![self.houseTotalPriceTextField.text isEqualToString:@""]) {
        [self calculateLoan];
        _isCalculate = YES;
    }else{
        _isCalculate = NO;
       [UIAlertControllerUtil generateInfoControllerWithTitle:@"房贷计算失败" message:@"请填写房产总额"];
    }
}

#pragma mark - Event Response
- (void)loanWayButtonEvent:(UIButton *)selectedBtn{
    UIView *groupBackView = [selectedBtn superview];
    
    if (groupBackView.tag == 1) {
        for (int i=0; i<_loanWayTitles.count;i++) {
            UIButton *button = [groupBackView viewWithTag:(i+3)];
            [button setSelected:NO];
        }
        if (selectedBtn.tag == 3) {
            _ratio = 0.5;
        }else{
            _ratio = 1;
        }
        self.bankRateLabel.text = [NSString stringWithFormat:@"%.2f",_ratio];
        
    }else{
        for (int i=0; i<_payLoanWayTitles.count;i++) {
            UIButton *button = [groupBackView viewWithTag:(i+3)];
            [button setSelected:NO];
        }
        if (selectedBtn.tag == 3) {
            self.bottomTintLabel.text = @"等额本金：每月还款额递减，所还总利息较低，前期还款额较大。";
            _isCapitalCalculate = YES;
        }else{
           self.bottomTintLabel.text = @"等额本息：每个月还款固定金额，每月还款额中的本金比重逐月递增，利息比重逐月递减。";
           _isCapitalCalculate = NO;
        }
        
    }
    [selectedBtn setSelected:YES];
    [self calculateLoan];
}

- (void)dismissKeyboard{
    [self endEditing:YES];
    [self.keyboardMaskView removeFromSuperview];
}

#pragma mark - Private
- (void)loadHouseLoanCalculateView{
    UIView *topBackView = [UIView new];
    UIView *loanMessageBackView = [UIView new];
    
    [self addSubview:topBackView];
    [self addSubview:loanMessageBackView];
    
    [self.chartsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(10);
        make.left.equalTo(self);
        make.width.equalTo(self).multipliedBy(1/3.0f);
        make.height.equalTo(self);
    }];
    
    [topBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(14);
        make.left.equalTo(self.chartsView.mas_right).offset(5);
        make.width.equalTo(self).multipliedBy(2/3.0f);
        make.height.equalTo(25);
    }];
    
    [loanMessageBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topBackView.mas_bottom).offset(TweentyOffsetViewMargin *2);
        make.left.equalTo(self.chartsView.mas_right).offset(5);
        make.width.equalTo(self).multipliedBy(2/3.0f);
        make.bottom.equalTo(self).offset(-10);
    }];
    
    [self loadTopViewWithBackView:topBackView];
    [self loadLoanMessageViewWithBackView:loanMessageBackView];
    
}

- (void)loadTopViewWithBackView:(UIView *)backView{
    UIView *priceTotalBackView = [UIView new];
    UIView *priceDiscountBackView = [UIView new];
    [backView addSubview:priceTotalBackView];
    [backView addSubview:priceDiscountBackView];
    
    [priceTotalBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backView).offset(TenOffsetViewMargin);
        make.top.bottom.equalTo(backView);
        make.width.equalTo(backView).multipliedBy(0.45);
    }];
    [priceDiscountBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(backView);
        make.right.equalTo(backView).offset(-TenOffsetViewMargin);
        make.width.equalTo(backView).multipliedBy(0.35);
    }];
    
    [TextFieldUtil loadTextFieldWithTitle:@"房产总额：" withUnit:@"万元" withTextField:self.houseTotalPriceTextField andBackView:priceTotalBackView];
    [TextFieldUtil loadTextFieldWithTitle:@"优惠：" withUnit:@"%" withTextField:self.priceDiscountTextField andBackView:priceDiscountBackView];

}

- (void)loadLoanMessageViewWithBackView:(UIView *)backView{
    UIView *downPayRatioBackView = [UIView new];
    downPayRatioBackView.backgroundColor = [UIColor whiteColor];
    downPayRatioBackView.layer.masksToBounds = YES;
    downPayRatioBackView.layer.cornerRadius = 3;
    UIView *loanYearsBackView = [UIView new];
    loanYearsBackView.backgroundColor = [UIColor whiteColor];
    loanYearsBackView.layer.masksToBounds = YES;
    loanYearsBackView.layer.cornerRadius = 3;
    UIView *bankRateBackView = [UIView new];
    bankRateBackView.backgroundColor = [UIColor whiteColor];
    bankRateBackView.layer.masksToBounds = YES;
    bankRateBackView.layer.cornerRadius = 3;
    
    UIView *loanWayBackView = [UIView new];
    UIView *payLoanWayBackView = [UIView new];
    
    [backView addSubview:downPayRatioBackView];
    [backView addSubview:loanYearsBackView];
    [backView addSubview:bankRateBackView];
    [backView addSubview:loanWayBackView];
    [backView addSubview:payLoanWayBackView];
    [backView addSubview:self.bottomTintLabel];
    
    [downPayRatioBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backView);
        make.left.equalTo(backView).offset(TenOffsetViewMargin);
        make.right.equalTo(backView).offset(-TenOffsetViewMargin);
        make.height.mas_equalTo(ScreenHeight*0.07);
    }];
    [loanYearsBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(downPayRatioBackView.mas_bottom).offset(TweentyOffsetViewMargin);
        make.centerX.equalTo(downPayRatioBackView);
        make.height.width.equalTo(downPayRatioBackView);
    }];
    [bankRateBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loanYearsBackView.mas_bottom).offset(TweentyOffsetViewMargin);
        make.centerX.equalTo(loanYearsBackView);
        make.height.width.equalTo(loanYearsBackView);
    }];
    [loanWayBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bankRateBackView.mas_bottom).offset(TweentyOffsetViewMargin*2);
        make.centerX.equalTo(bankRateBackView);
        make.width.equalTo(bankRateBackView);
        make.height.mas_equalTo(ScreenHeight*0.06);
    }];
    [payLoanWayBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loanWayBackView.mas_bottom).offset(TweentyOffsetViewMargin);
        make.centerX.equalTo(loanWayBackView);
        make.height.width.equalTo(loanWayBackView);
    }];
    
    NSArray *downPayRatios = @[@"3成",@"4成",@"5成",@"6成",@"7成",@"8成"];
    NSMutableArray *loanYears = [NSMutableArray array];
    
    for (int i=1; i<30; i++) {
        NSString *loanYear = [NSString stringWithFormat:@"%d年(%d期)",i,i*12];
        [loanYears addObject:loanYear];
    }
    
    __weak typeof(self) weakSelf = self;
    _downPayRateDropMenu = [DropdownMenuViewUtil loadDropdownMenuViewWithTitle:@"首付比例：" withDropdownMenuContentTitleArray:downPayRatios andBackView:downPayRatioBackView];
    _downPayRateDropMenu.selectedAtIndex = ^(int index){
        _firstPayRatio = (CGFloat)(index + 3) / 10.0;
        [weakSelf calculateLoan];
    };
//    _downPayRateDropMenu.width = 100;
    _loanYearsDropMenu = [DropdownMenuViewUtil loadDropdownMenuViewWithTitle:@"贷款年限：" withDropdownMenuContentTitleArray:loanYears andBackView:loanYearsBackView];
    _loanYearsDropMenu.selectedAtIndex = ^(int index){
        _period = (index+1)*12;
        [weakSelf calculateLoan];
    };
    [LabelUtil loadLabelWithTitle:@"银行利率：" withUnit:@"%" withLabel:self.bankRateLabel andBackView:bankRateBackView];
    UILabel *titleLabel = [bankRateBackView viewWithTag:TitleLabelTag];
    titleLabel.textColor = TextColor80;
    [titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bankRateBackView).offset(FiveOffsetViewMargin);
    }];
    UILabel *unitLabel = [bankRateBackView viewWithTag:UnitLabelTag];
    unitLabel.textColor = TextColor80;
    [unitLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bankRateBackView).offset(-FifteenoffsetViewMargin);
    }];
    
    _loanWayTitles = @[@"商业贷款",@"公积金贷款"];
    [self loadBooleanSelectButtonGroupWithTitle:@"贷款方式：" withGroupTitles:_loanWayTitles withGroupTag:1 andBackView:loanWayBackView];
    _payLoanWayTitles = @[@"等额本金",@"等额本息"];
    [self loadBooleanSelectButtonGroupWithTitle:@"还款方式：" withGroupTitles:_payLoanWayTitles withGroupTag:2 andBackView:payLoanWayBackView];
    UIView *buttonGroupBackView = [payLoanWayBackView viewWithTag:2];
    [self.bottomTintLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(payLoanWayBackView.mas_bottom).offset(FiveOffsetViewMargin);
        make.left.equalTo(buttonGroupBackView);
        make.right.equalTo(payLoanWayBackView);
    }];
}

- (void)loadBooleanSelectButtonGroupWithTitle:(NSString *)title withGroupTitles:(NSArray *)titles withGroupTag:(NSInteger)groupTag andBackView:(UIView *)backView{
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = title;
    titleLabel.font = TextFont14;
    titleLabel.textColor = TextColor80;
    UIView *buttonGroupBackView = [UIView new];
    buttonGroupBackView.tag = groupTag;
    [backView addSubview:titleLabel];
    [backView addSubview:buttonGroupBackView];
    
    CGRect titleRect = [titleLabel calculateBounds];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.equalTo(backView);
        make.width.equalTo(titleRect.size.width);
    }];
    [buttonGroupBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLabel.mas_right);
        make.top.bottom.right.equalTo(backView);
    }];
    [ButtonUtil loadBooleanSelectButtonGroupWithTitles:titles withSelectedColor:SelectBackgroundColor230 withUnSelectedColor:[UIColor whiteColor] withSelectTextColor:IndicatorColor52 withUnSelectTextColor:TextColor80 andBackView:buttonGroupBackView];
    
    for (int i=0; i<titles.count; i++) {
        UIButton *button = (UIButton *)[buttonGroupBackView viewWithTag:(i+3)];
        button.titleLabel.font = TextFont14;
        [button addTarget:self action:@selector(loanWayButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)calculateLoan{
    if ([self.houseTotalPriceTextField.text isEqualToString:@""]) {
        [UIAlertControllerUtil generateInfoControllerWithTitle:@"房贷计算失败" message:@"请填写房产总额"];
        return;
    }
    
    if ((![self.priceDiscountTextField.text isEqualToString:@""])&&([self.priceDiscountTextField.text floatValue] >= 100||[self.priceDiscountTextField.text floatValue]<0)) {
        [UIAlertControllerUtil generateInfoControllerWithTitle:@"房贷计算失败" message:@"请输入正确的优惠比例（0~100）(不包括100)"];
        return;
    }
    
    _loanCalculateUtil.houseTotalPrice = [self.houseTotalPriceTextField.text floatValue];
    _loanCalculateUtil.discountRatio = [self.priceDiscountTextField.text isEqualToString:@""]?0:([self.priceDiscountTextField.text floatValue]/100.0);
    _loanCalculateUtil.firstPaymentRatio = _firstPayRatio;
    _loanCalculateUtil.period = _period;
    _loanCalculateUtil.ratio = _ratio/100.0;
    _loanCalculateUtil.loanCalculateType = _isCapitalCalculate == YES? AverageCapital:AverageCapitalPlusInterest;
    [_loanCalculateUtil calculate];
    
    HouseLoanCalculateChartsModel *model = [HouseLoanCalculateChartsModel new];
    model.downPayment = _loanCalculateUtil.firstPayment;
    model.loanTotal = _loanCalculateUtil.loanTotalMoney;
    model.loanInterest = _loanCalculateUtil.totalInterest;
    model.loanDiscount = _loanCalculateUtil.disccountMoney;
    model.pricePerMonth = _loanCalculateUtil.averagePayMoneyPerMonth;
    [self.chartsView setModel:model];
}

#pragma mark - Getter
- (HouseLoanCalculateChartsView *)chartsView{
    if (_chartsView == nil) {
        _chartsView = [HouseLoanCalculateChartsView new];
        [self addSubview:_chartsView];
    }
    
    return _chartsView;
}

- (UITextField *)houseTotalPriceTextField{
    if (_houseTotalPriceTextField == nil) {
        _houseTotalPriceTextField = [UITextField new];
        _houseTotalPriceTextField.textColor = TextColor80;
        _houseTotalPriceTextField.font = TextFont14;
        _houseTotalPriceTextField.layer.masksToBounds = YES;
        _houseTotalPriceTextField.layer.cornerRadius = 3;
        _houseTotalPriceTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 0)];
        _houseTotalPriceTextField.leftViewMode = UITextFieldViewModeAlways;
        _houseTotalPriceTextField.backgroundColor = [UIColor whiteColor];
        _houseTotalPriceTextField.delegate = self;
    }
    
    return _houseTotalPriceTextField;
}

- (UITextField *)priceDiscountTextField{
    if (_priceDiscountTextField == nil) {
        _priceDiscountTextField = [UITextField new];
        _priceDiscountTextField.backgroundColor = [UIColor whiteColor];
        _priceDiscountTextField.textColor = TextColor80;
        _priceDiscountTextField.font = TextFont14;
        _priceDiscountTextField.layer.masksToBounds = YES;
        _priceDiscountTextField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 0)];
        _priceDiscountTextField.leftViewMode = UITextFieldViewModeAlways;
        _priceDiscountTextField.layer.cornerRadius = 3;
        _priceDiscountTextField.delegate = self;
    }
    
    return _priceDiscountTextField;
}

- (UILabel *)bankRateLabel{
    if (_bankRateLabel == nil) {
        _bankRateLabel = [UILabel new];
        _bankRateLabel.text = @"0.5";
        _bankRateLabel.textAlignment = NSTextAlignmentCenter;
        _bankRateLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
        _bankRateLabel.textColor = TextColor120;
    }
    
    return _bankRateLabel;
}

- (UILabel *)bottomTintLabel{
    if (_bottomTintLabel == nil) {
        _bottomTintLabel = [UILabel new];
        _bottomTintLabel.font = TextFont12;
        _bottomTintLabel.textColor = TextColor150;
        _bottomTintLabel.text = @"等额本金：每月还款额递减，所还总利息较低，前期还款额较大。";
        _bottomTintLabel.numberOfLines = 0;
    }
    
    return _bottomTintLabel;
}

- (UIView *)keyboardMaskView{
    if (_keyboardMaskView == nil) {
        _keyboardMaskView = [UIView new];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
        [_keyboardMaskView addGestureRecognizer:tapGesture];
    }
    return _keyboardMaskView;
}


#pragma mark - Setter
- (void)setHouseTotalPrice:(NSString *)houseTotalPrice{
    _houseTotalPrice = houseTotalPrice;
    self.houseTotalPriceTextField.text = _houseTotalPrice;
    if (_houseTotalPrice != nil) {
        [self calculateLoan];
    }
}

@end
